package com.wuda.utils;

import java.sql.*;

public class Base {
	private static final String driver = DBConstants.driver;
	private static final String url = DBConstants.url;
	private static final String username = DBConstants.username;
	private static final String password = DBConstants.password;
	/**
	 * 获取数据库连接
	 *
	 * @return
	 * @throws ClassNotFoundException
	 */
	public static Connection getConnection() throws ClassNotFoundException, SQLException {
		Class.forName(driver);
		return DriverManager.getConnection(url, username, password);
	}

	/**
	 * 公共查询
	 *
	 * @param connection 连接
	 * @param sql 查询SQL
	 * @param params 查询参数
	 * @return ResultSet 结果集
	 * @throws SQLException
	 */
	public static ResultSet executeQuery(Connection connection, String sql, Object[] params) throws SQLException {
		PreparedStatement preparedStatement = connection.prepareStatement(sql);
		for (int i = 0; params != null && i < params.length; i++) {
			preparedStatement.setObject(i + 1, params[i]);
		}
		return preparedStatement.executeQuery();
	}

	/**
	 * 公共修改方法
	 *
	 * @param connection 连接
	 * @param sql 修改SQL
	 * @param params 修改参数
	 * @return int 受影响的行数
	 * @throws SQLException
	 */
	public static int executeUpdate(Connection connection, String sql, Object[] params) throws SQLException {
		PreparedStatement preparedStatement = connection.prepareStatement(sql);
		for (int i = 0; params != null && i < params.length; i++) {
			preparedStatement.setObject(i + 1, params[i]);
		}
		return preparedStatement.executeUpdate();
	}






	/**
	 * 释放资源
	 *
	 * @param connection 连接
	 * @param preparedStatement 预处理语句
	 * @param resultSet 结果集
	 * @return boolean 是否成功
	 * @throws SQLException
	 */
	public static boolean closeResource(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet)
			throws SQLException {
		boolean flag = true;
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				e.printStackTrace();
				flag = false;
			}
		}
		if (preparedStatement != null) {
			try {
				preparedStatement.close();
			} catch (SQLException e) {
				e.printStackTrace();
				flag = false;
			}
		}
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
				flag = false;
			}
		}
		return flag;
	}
}
